import { Message } from '@arco-design/web-vue';
import { defineStore } from 'pinia';
import { ref, computed, readonly } from 'vue';
import { useRouter } from 'vue-router';

import { authApi, adminApi } from '@/api';
import type { AdminLoginRequest, AdminUserInfo, TenantInfo } from '@/api/auth';
import { AdminType, PermissionChecker } from '@/types/permission';

export const useUserStore = defineStore(
  'user',
  () => {
    const router = useRouter();

    // State
    const token = ref<string | null>(null);
    const userInfo = ref<AdminUserInfo | null>(null);
    const currentTenant = ref<TenantInfo | null>(null);
    const availableTenants = ref<TenantInfo[]>([]);
    const isLoading = ref(false);
    const isInitialized = ref(false);

    // Getters - 基于AdminType的权限计算属性
    const isLoggedIn = computed(() => !!token.value);
    const adminType = computed(() => userInfo.value?.adminType);
    const isSuperAdmin = computed(() => adminType.value === AdminType.SUPER_ADMIN);
    const isSchoolAdmin = computed(() => adminType.value === AdminType.SCHOOL_ADMIN);
    const managedTenantIds = computed(() => userInfo.value?.tenantIds || []);
    const userName = computed(() => userInfo.value?.name || userInfo.value?.username || '');

    const hasTenantAccess = computed(() => (tenantId: string) => {
      if (!adminType.value) return false;
      return PermissionChecker.hasTenantAccess(adminType.value, managedTenantIds.value, tenantId);
    });

    // 租户相关计算属性
    const canAccessAllTenants = computed(() => isSuperAdmin.value);
    const accessibleTenants = computed(() => {
      if (isSuperAdmin.value) {
        return availableTenants.value;
      }
      return availableTenants.value.filter((tenant) => managedTenantIds.value.includes(tenant.id));
    });

    const userRole = computed(() => adminType.value || '');
    const tenantList = computed(() => availableTenants.value || []);

    // Actions
    const setToken = (newToken: string) => {
      token.value = newToken;
      // 存储到localStorage以便请求拦截器使用
      localStorage.setItem('access_token', newToken);
    };

    const setUserInfo = (user: AdminUserInfo) => {
      userInfo.value = user;
      if (user.currentTenant) {
        currentTenant.value = user.currentTenant;
      }
      if (user.availableTenants) {
        availableTenants.value = user.availableTenants;
      }
    };

    const setCurrentTenant = (tenant: TenantInfo) => {
      currentTenant.value = tenant;
    };

    const setAvailableTenants = (tenants: TenantInfo[]) => {
      availableTenants.value = tenants;
    };

    // 管理员登录
    const adminLogin = async (loginData: AdminLoginRequest) => {
      try {
        isLoading.value = true;
        const response = await authApi.adminLogin(loginData);

        if (response.token) {
          setToken(response.token);
        }

        if (response.user) {
          setUserInfo(response.user);
        }

        Message.success('登录成功');
        return response;
      } finally {
        isLoading.value = false;
      }
    };

    // 切换租户
    const switchTenant = async (tenantId: string) => {
      try {
        isLoading.value = true;
        const response = await authApi.switchTenant({ tenantId });

        if (response.token) {
          setToken(response.token);
        }

        if (response.tenant) {
          setCurrentTenant(response.tenant);
        }

        Message.success(`已切换到租户: ${response.tenant.name}`);
        return response;
      } catch (error) {
        Message.error('切换租户失败');
        throw error;
      } finally {
        isLoading.value = false;
      }
    };

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const user = await authApi.getUserInfo();
        setUserInfo(user);
        return user;
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    // 获取可管理租户列表
    const fetchAvailableTenants = async () => {
      try {
        const response = await adminApi.getMyTenants();
        setAvailableTenants(response.data);
        return response.data;
      } catch (error) {
        console.error('获取租户列表失败:', error);
        throw error;
      }
    };

    // 退出登录
    const logout = async () => {
      try {
        await authApi.logout();
      } catch (error) {
        console.error('退出登录错误:', error);
        // 即使API调用失败，也要清除本地数据并跳转到登录页
      } finally {
        clearUserData();
        Message.success('已退出登录');
        router.push({ name: 'Login' }); // 修正路由名称，使用大写L
      }
    };

    // 清除用户数据
    const clearUserData = () => {
      token.value = null;
      userInfo.value = null;
      currentTenant.value = null;
      availableTenants.value = [];
      localStorage.removeItem('access_token');
      localStorage.removeItem('refresh_token');
    };

    // 初始化用户数据（从本地存储恢复）
    const initUserData = async () => {
      try {
        const savedToken = localStorage.getItem('access_token');
        if (savedToken) {
          token.value = savedToken;
          // 如果有 token 但没有用户信息，尝试获取
          if (!userInfo.value) {
            try {
              await fetchUserInfo();
            } catch (error) {
              console.warn('初始化时获取用户信息失败，可能token已过期:', error);
              clearUserData();
            }
          }
        }
      } catch (error) {
        console.error('初始化用户数据失败:', error);
      } finally {
        isInitialized.value = true;
      }
    };

    // 检查登录状态
    const checkLoginStatus = async () => {
      if (!token.value) {
        return false;
      }

      try {
        await fetchUserInfo();
        return true;
      } catch {
        clearUserData();
        return false;
      }
    };

    return {
      // State
      token: readonly(token),
      userInfo: readonly(userInfo),
      currentTenant: readonly(currentTenant),
      availableTenants: readonly(availableTenants),
      isLoading: readonly(isLoading),
      isInitialized: readonly(isInitialized),

      // Getters - 基于AdminType的权限计算属性
      isLoggedIn,
      adminType,
      isSuperAdmin,
      isSchoolAdmin,
      managedTenantIds,
      userName,
      hasTenantAccess,
      canAccessAllTenants,
      accessibleTenants,

      // 兼容性计算属性
      userRole,
      tenantList,

      // Actions
      setToken,
      setUserInfo,
      setCurrentTenant,
      adminLogin,
      switchTenant,
      fetchUserInfo,
      fetchAvailableTenants,
      logout,
      clearUserData,
      initUserData,
      checkLoginStatus
    };
  },
  {
    persist: {
      key: 'user-store',
      storage: localStorage,
      pick: ['userInfo', 'currentTenant', 'availableTenants']
    }
  }
);
